﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Composite.Data.Types;
using Composite.Data;
using System.Text.RegularExpressions;
using LCA.Common.Extensions;

namespace LCA.Admin.FormControls
{
    public partial class FileSelector : System.Web.UI.UserControl
    {
        public Guid? SelectedImageId
        {
            get { return (Guid?)ViewState["SelectedImageId"]; }
            set { ViewState["SelectedImageId"] = value; }
        }

        protected IMediaFile SelectedImage
        {
            get
            {
                if (this.SelectedImageId != null)
                {
                    return DataFacade.GetData<IMediaFile>()
                                     .Where(x => x.Id == this.SelectedImageId)
                                     .FirstOrDefault();
                }

                return null;
            }
        }

        protected string SelectedImageLabel
        {
            get
            {
                var media = this.SelectedImage;
                if (media != null)
                {
                    return media.FileName;
                }

                return null;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
            }
            else
            {
                var mediaUrl = HttpContext.Current.Server.UrlDecode(Request.Form[this.ClientID]);
                var mediaId = Regex.Replace(mediaUrl, @"\~\/media\(([0-9a-fA-F\-]+)\)", "$1").ToGuid();
                this.SelectedImageId = mediaId;
            }
        }
    }
}
